import React, { useEffect, useRef, useState, useMemo } from 'react';
import styles from './index.module.less';
import FormGroup, { FormListItem } from '@/components/form-group';
import ButtonFooter from '@/components/button-footer';
import ContentCard from '../matter-card';
import DocStandard from './standard';
import { GenerateUUID } from '@/utils';
import { MatterItem, StandardItem } from '@/pages/official-doc/interface';
import classnames from 'classnames';
import { FormContentType } from '@/pages/official-doc/components/doc-content/interface.d';
import { checkMoneyFormat } from '@/utils/form-rules';
// import { orgData } from '@/services/design';
import { IOrgTreeItem } from '@/components/ContractSelectModal';
import { useSelector } from 'react-redux';
import { IS_COSTUM_STANDARD } from '@/pages/official-doc/constants';
// import history from '@/utils/history';

export interface Props {
  content: MatterItem;
  handleChange?: (data: MatterItem, type?: 'back') => void;
}

const DocMatter: React.FC<Props> = (props) => {
  const { content, handleChange } = props;
  // matterTotal=-1， 不限制额度，回显''
  content.matterTotal = content.matterTotal === -1 ? '' : content.matterTotal;

  const formRef: React.MutableRefObject<any> = useRef();
  const [contentData, setContentData] = useState({} as MatterItem);
  const [target, setTarget] = useState({} as StandardItem);
  const [showNextForm, setShowNextForm] = useState(false);
  const { orgTree } = useSelector((state: any) => ({
    orgTree: state.common.orgTree
  }));
  useEffect(() => {
    setContentData(content);
    formRef.current.setValues(content);
  }, [content]);

 

  const handleOk = async () => {
    let data = await formRef.current.getValues();
    console.log('data,handleOk', data);
    data = {
      ...data,
      manager: formatList(data.manager),
      managerId: data.manager?.[0]?.key,
      managerName: data.manager?.[0]?.title,
      lookUpUserList: formatList(data.lookUpUserList),
      isCustomStandard: data.isCustomStandard
    };
    data.matterTotal = data.matterTotal === '' ? -1 : data.matterTotal;
    console.log('data----------------{}', data);
    formRef.current.resetValues();
    handleChange && handleChange({ ...contentData, ...data });
  };

  const formatList = (list: IOrgTreeItem[]) => {
    if (!list) return undefined;
    return list.map((item: IOrgTreeItem) => ({
      id: item.key || item.id,
      name: item.title || item.name,
      userOrgType: item.type || item.userOrgType
    }));
  };

  const saveData = async () => {
    const data = await formRef.current.getData();
    const newFormData = {
      ...contentData,
      ...data
    };
    setContentData(newFormData);
  };

  const goNextForm = () => {
    saveData();
    if (!contentData.standardAddList?.length) {
      contentData.standardAddList = [] as StandardItem[];
    }
    // 标准列表中先新增一项，标准页面点击确认添加后更新这一项的内容，标准页面点击返回时需要排除这一项
    contentData.standardAddList.push({
      id: GenerateUUID(),
      sort: contentData.standardAddList.length + 1
    } as StandardItem);
    setTarget(
      contentData.standardAddList[contentData.standardAddList.length - 1]
    );
    setShowNextForm(true);
  };

  const handleSetStandard = (data: StandardItem, type?: 'back') => {
    const standardAddList: StandardItem[] = [];
    contentData.standardAddList?.forEach((item: StandardItem) => {
      if (item.id === target.id) {
        if (type === 'back') {
          if (!item.standardName) {
            // 不存在标准名称，说明是新添加的数据，不存入数组（这种判断是否为新添加数据的方式有点坑）
            return;
          }
          return standardAddList.push(item);
        }
        return standardAddList.push({ ...item, ...data });
      }
      return standardAddList.push(item);
    });
    setContentData({ ...contentData, standardAddList });
    setShowNextForm(false);
  };

  const handleStandardDelete = (id: string) => {
    const standardAddList = contentData.standardAddList?.filter(
      (item: StandardItem) => {
        if (id === item.id) {
          return false;
        }
        return true;
      }
    );
    setContentData({ ...contentData, standardAddList });
  };

  const handleStandardClick = (data: any) => {
    console.log('handleStandardClick进来');
    let activeTarget;
    // console.log(contentData.standardAddList, data);
    contentData.standardAddList?.forEach((item: StandardItem) => {
      if (item.id === data.id) {
        activeTarget = item;
        // console.log('activeTarget: ', item);
      }
    });
    if (activeTarget !== undefined) {
      setTarget(activeTarget);
      setShowNextForm(true);
    }
  };

  const getList = ({
    manager,
    lookUpUserList,
    orgTreeData,
    isCustomStandard
  }) => {
    const formList: FormListItem[] = [
      {
        valueKey: 'matterName',
        label: '事项名称',
        type: 'input',
        options: {
          rules: [
            { required: true, message: '请填写事项名称' },
            { whitespace: true, message: '事项名称不能为空' }
          ]
        },
        cellProps: { maxLength: 64 }
      },
      {
        valueKey: 'manager',
        label: '经办人',
        type: 'treeSelecter',
        cellProps: {
          extra: '请选择（选填）',
          receiveData: manager || [
            {
              id: content.managerId,
              name: content.managerName,
              userOrgType: 2
            }
          ],
          type: 'person',
          mode: 'single',
          orgData: orgTreeData
        }
      },
      {
        valueKey: 'lookUpUserList',
        label: '可查阅人',
        type: 'treeSelecter',
        cellProps: {
          extra: '请选择（选填）',
          receiveData: lookUpUserList,
          type: 'all',
          mode: 'multiple',
          orgData: orgTreeData
        }
      },
      {
        valueKey: 'matterTotal',
        label: '事项总额',
        type: 'input',
        options: {
          rules: [{ validator: checkMoneyFormat }]
        },
        cellProps: {
          placeholder: '请输入（选填）',
          type: 'money',
          moneyKeyboardAlign: 'left',
          autoAdjustHeight: true,
          maxLength: 10
        }
      },
      {
        valueKey: 'remark',
        label: '备注',
        type: 'input',
        cellProps: { placeholder: '请输入（选填）', maxLength: 200 }
      },
      {
        valueKey: 'isCustomStandard',
        label: '允许自定义标准',
        type: 'radioSelect',
        options: { rules: [{ required: true, message: '请选择自定义标准' }] },
        pickerOptions: IS_COSTUM_STANDARD,
        cellProps: { placeholder: '请选择（必填）' }
      }
    ];
    return formList;
  };

  const getListMemo = useMemo(
    () =>
      getList({
        orgTreeData: orgTree,
        manager: content.manager,
        lookUpUserList: content.lookUpUserList,
        isCustomStandard: content.isCustomStandard
      }),
    [orgTree, content.manager, content.lookUpUserList]
  );

  return (
    <React.Fragment>
      <div className={classnames(styles.wrap, showNextForm ? styles.hide : '')}>
        {console.log('formList', { getListMemo })}

        <FormGroup routeBlock ref={formRef} formList={getListMemo} />
        {contentData.standardAddList?.map(
          (item: StandardItem, index: number) => (
            <ContentCard
              key={index}
              type={FormContentType.CONTENT}
              data={item}
              handleDelete={handleStandardDelete}
              handleClick={handleStandardClick}
            />
          )
        )}
        <div className={styles.addItem} onClick={goNextForm}>
          + 添加标准明细
        </div>
        <ButtonFooter
          data={[
            {
              text: '确定',
              onClick: handleOk
            }
          ]}
        />
      </div>
      {/* <div className={classnames(!showNextForm ? styles.hide : '')}> */}
      {
        showNextForm && (
          <DocStandard standard={target} handleChange={handleSetStandard} />
        )
      }
      {/* </div> */}
    </React.Fragment >
  );
};

export default DocMatter;
